package client.comm.baoding.fragment

import android.content.Intent
import android.view.View
import android.view.ViewGroup
import androidx.core.view.ViewCompat
import client.comm.baoding.R
import client.comm.baoding.adapter.main.JyGoodAdapter
import client.comm.baoding.api.bean.ShopingBean
import client.comm.baoding.api.bean.TradeIndex
import client.comm.baoding.databinding.FragmentTabjyBinding
import client.comm.baoding.dialog.SelectSkuDialog
import client.comm.baoding.ui.ConfirmOrderActivity
import client.comm.baoding.ui.GoodsDetailActivity
import client.comm.baoding.ui.GoodsDetailTradeActivity
import client.comm.baoding.ui.vm.MainViewModel
import client.comm.commlib.base.BaseActivity
import client.comm.commlib.base.BaseFragment
import client.comm.commlib.base.SyBannerAdapter
import client.comm.commlib.comm_ui.draw.SpaceItemDecoration
import client.comm.commlib.getScreenWidth
import client.comm.commlib.toast.toast
import client.comm.commlib.utils.Util
import client.comm.commlib.widget.EmptyLayout
import com.bumptech.glide.request.RequestOptions
import com.youth.banner.indicator.CircleIndicator
import java.util.*

class TabJyFragment : BaseFragment<FragmentTabjyBinding, MainViewModel>() {

    override fun getViewId(): Int {
        return R.layout.fragment_tabjy
    }

    override fun initViewModel(): MainViewModel = createViewModel()

    val jyAdapter: JyGoodAdapter by lazy {
        JyGoodAdapter(requireContext(), mImgLoader).apply {
            itemClick = {
//                if (it.is_type == 1) {
//                    context?.startActivity(Intent(context, GoodsDetailTradeActivity::class.java).apply {
//                        putExtra("goodsId", "${it.goods_id}")
//                    })
//                } else {
                    context?.startActivity(Intent(context, GoodsDetailActivity::class.java).apply {
                        putExtra("goodsId", "${it.goods_id}")
                    })
//                }
            }

            onBuy = {
//                if (it.is_type == 1) {
//                    context?.startActivity(Intent(context, GoodsDetailTradeActivity::class.java).apply {
//                        putExtra("goodsId", "${it.goods_id}")
//                    })
//                } else {
                    context?.startActivity(Intent(context, GoodsDetailActivity::class.java).apply {
                        putExtra("goodsId", "${it.goods_id}")
                    })
//                }

                /*SelectSkuDialog(requireContext() as BaseActivity<*, *>,"1").apply {
                    id = it.goods_id
                    price = it.price.toDouble()
                    imgUrl = "${it.goods_img}"
                    name = "${it.name}"
                    var good_item = it
                    ok = {
                        var num = 0
                        try {
                            num = it.toInt()
                        } catch (e: Exception) {
                        }
                        if (num > 0) {
                            val list = ArrayList<ShopingBean>()
                            val bean = ShopingBean(
                                goods_id = id,
                                goods_img = imgUrl,
                                name = name,
                                price = good_item.price!!.toDouble(),
                                shopping_id = "",
                                num = it.toInt(),
                                store_id = "",
                                sku = good_item.sku!!,
                                )
                            list.add(bean)
                            startActivity(Intent(context, ConfirmOrderActivity::class.java).apply {
                                putExtra("list", list)
                            })
                        } else {
                            toast("请输入数量")
                        }
                    }
                }.show()*/
            }
        }
    }

    override fun initWidget() {
        binding.statusBar.post {
            val h = Util.getStatusBarHeight(requireContext())
            val p = binding.statusBar.layoutParams
            p.height = h
            binding.statusBar.layoutParams = p
            Util.setBg(resources!!.getColor(R.color.white), requireActivity().window)
            val controller = ViewCompat.getWindowInsetsController(binding.root)
            controller?.isAppearanceLightStatusBars = true
        }
        binding.event = this

        viewModel.tradeCall.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    val list = it.data?.goods_list as MutableList<TradeIndex.Goods?>?
                    if (viewModel.pageTrade.value == 1) {
                        jyAdapter.submitList(list)
                    } else {
                        jyAdapter.appendList(list)
                    }

                    val bannerList = it.data!!.banner_list as ArrayList<TradeIndex.Banner>
                    bannerList?.let {
                        setBanner(bannerList)
                    }

                    if (list != null && list.size > 0) {
                        if (list.size < 10) {
                            jyAdapter.hasMoreState.value = false
                        }
                        binding.emptyLayout.visibility = View.GONE
                    } else {
                        if (jyAdapter.itemCount == 0) {
                            binding.emptyLayout.errorType = EmptyLayout.NODATA
                        }
                        jyAdapter.hasMoreState.value = false
                    }
                } else {
                    if (jyAdapter.itemCount == 0) {
                        binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
                    }
                }
            }
        })
    }

    override fun initData() {
        super.initData()
        binding.emptyLayout.setOnClickListener {
            viewModel.pageTrade.value = 0
            viewModel.tradeIndex()
        }
        binding.recyclerView.addItemDecoration(SpaceItemDecoration(10))
        binding.recyclerView.adapter = jyAdapter
        binding.recyclerView.onLoadMore = {
            if (jyAdapter.hasMoreState.value!! && !viewModel.isTradeLoading.value!!) {
                viewModel.tradeIndex()
            }
        }
        binding.refreshLayout.setOnRefreshListener {
            jyAdapter.hasMoreState.value = true
            viewModel.pageTrade.value = 0
            viewModel.tradeIndex()
        }
        viewModel.isTradeLoading.observe(this, {
            if (!it) {
                binding.refreshLayout.isRefreshing = false
            }
        })
//        if (viewModel.pageTrade.value == null) {
//            viewModel.tradeIndex()
//        }

        viewModel.pageTrade.value = 0
        viewModel.tradeIndex()
    }

    private fun setBanner(bannerList: ArrayList<TradeIndex.Banner>) {
        if (bannerList != null && bannerList.size > 0) {
            val width = getScreenWidth(requireContext())
            val params: ViewGroup.LayoutParams = binding.banner.getLayoutParams()
            params.height = (width * 575 / 1400f).toInt()
            binding.banner.layoutParams = params
            binding.banner.indicator = CircleIndicator(requireContext())
            val list = bannerList
            binding.banner.setAdapter(object : SyBannerAdapter<TradeIndex.Banner>(list) {
                override fun onBindView(
                    holder: BannerViewHolder?,
                    data: TradeIndex.Banner?,
                    position: Int,
                    size: Int
                ) {
                    mImgLoader.load(data?.image_url)
                        .apply(RequestOptions().error(R.mipmap.ic_launcher)).into(
                            holder!!.imageView
                        )
                }
            })
            binding.banner.start()
        }
    }


}